<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search
      ref="customSearchRef"
      v-slot="{ params }"
      :default-params="{ adCode: [], inGh: '0', deleted: '0', cjsj: [], orderStage:'5' }"
      @submit="handleSeachTable"
    >
      <t-col :span="3">
        <t-form-item label="订单类型" name="decorationType">
          <t-select
            v-model:value="params.decorationType"
            :options="dictionaryStore.get('decoration_order_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="订单阶段" name="orderStage">
          <t-select
            v-model:value="params.orderStage"
            :options="[...dictionaryStore.get('decoration_order_stage'),{ label: '在途(上报至设计阶段)', value: '5' }]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户等级" name="customerLevel">
          <t-select
            v-model:value="params.customerLevel"
            :options="dictionaryStore.get('decoration_order_customer_level')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="手机号码" name="phone">
          <t-input v-model:value="params.phone" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="微信号码" name="wxCode">
          <t-input v-model:value="params.wxCode" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="来源渠道" name="channelSource">
          <t-select
            v-model:value="params.channelSource"
            :options="channelList"
            :keys="{ value: 'id', label: 'name' }"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="房屋户型" name="houseType">
          <t-select
            v-model:value="params.houseType"
            :options="dictionaryStore.get('decoration_order_house_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属部门" name="deptId">
          <t-cascader
            v-model:value="params.deptId"
            :options="simpleDeptTree"
            :keys="{ label: 'name', value: 'id' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            @change="(val, ctx) => handleGetSaleList(val)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3" v-if="params.deptId">
        <t-form-item label="客服" name="saleId">
          <t-select
            v-model:value="params.saleId"
            :options="saleList"
            :keys="{ label: 'nickname', value: 'id' }"
            placeholder="请选择客服"
            clearable
            filterable
            @clear="params.saleId = null"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="上报人" name="creator">
          <t-select
            v-model:value="params.creator"
            :options="reporteList"
            :keys="{ label: 'nickname', value: 'id' }"
            placeholder=""
            clearable
            filterable
            @clear="params.creator = null"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="是否公海" name="inGh">
          <t-select
            v-model:value="params.inGh"
            :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' },
            ]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="是否废单" name="deleted">
          <t-select
            v-model:value="params.deleted"
            :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' },
            ]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属公司" name="companyId">
          <t-select
          v-model:value="params.companyId"
          :options="companyList"
          :keys="{ label: 'name', value: 'id' }"
          placeholder=""
          filterable
          clearable
        />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="cjsj">
          <t-date-range-picker
            allow-input
            v-model:value="params.cjsj"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
            @change="
              (value) => {
                const [beginTime, endTime] = value;
                params.beginTime = beginTime;
                params.endTime = endTime;
              }
            "
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      v-model:selected-row-keys="selectedRowKeys"
      row-key="id"
      :columns="columns"
      :api="basicOrderCRUD.page"
      column-controller-key="basicOrderList"
      :reserve-selected-row-on-paginate="true"
      :on-before-set-data="handleTableSetData"
      @request-success="handleTableRequestSuccess"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button v-permission="['system:order:create']" @click="handleOpenDialog('create', { adCode: [] })">
            新建订单
          </t-button>
          <!-- 转派客服 -->
          <transfer-sale :ids="selectedRowKeys" batch @request-success="handleDialogRequestSuccess" />
          <!-- 转派设计师 -->
          <!-- <transfer-designer :ids="selectedRowKeys" batch @request-success="handleDialogRequestSuccess" /> -->
          <span v-if="hasData" style="margin-left: 10px;">
            <span v-for="stage in processedStages" :key="stage.value" class="stage-item">
              <span>{{ stage.label }}</span>
              <t-link theme="primary" v-if="stage.count > 0" @click="handleClick(stage.value, stage.ids)">
                {{ stage.count }}条；
              </t-link>
       
            </span>
          </span>
          <span v-if="hasData" style="margin-left: 10px;">
            <span v-for="stage in designStages" :key="stage.value" class="stage-item">
              <span>{{ stage.label }}</span>
              <t-link theme="primary" v-if="stage.count > 0" @click="handleClick(stage.value, stage.ids)">
                {{ stage.count }}条；
              </t-link>
       
            </span>
          </span>
          <span v-if="hasData&&overdueStages.length>0">
            其中
            <span v-for="stage in overdueStages" :key="stage.value" class="stage-item">
        <span>{{ stage.label }}</span>
        <t-link theme="primary"  @click="handleClick(stage.value, stage.ids)">
          {{ stage.count  }}条；
        </t-link>

      </span>
          </span>
        </div>
      </template>
      <template #decorationType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_type', row.decorationType) }}
      </template>
      <template #orderStage="{ row }">
        {{ dictionaryStore.analysis('decoration_order_stage', row.orderStage) }}
      </template>
      <template #customerLevel="{ row }">
        {{ dictionaryStore.analysis('decoration_order_customer_level', row.customerLevel) }}
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #channelSource="{ row }">
        {{ channelList.find((item) => item.id.toString() === row.channelSource)?.name }}
      </template>
      <template #propertyName="{ row }">
        <div>
          {{ propertyInfoList.find((item) => item.id === row.propertyName)?.name }}
          <span style="color: gray;">{{ row.address }}</span>
        </div>
        <span v-if="row.shangBaoCount">上报：{{ row.shangBaoCount }}</span>
        <span v-if="row.engineeringCount">施工：{{ row.engineeringCount }}</span>
      </template>
      <template #houseType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
      </template>
      <template #reporterName="{ row }">
        {{ userStore.getUserNameById(row.creator) }}
      </template>
      <template #saleName="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerName="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #lastMessageTime="{ row }">
        {{ row.lastMessageTime&&dayjs(row.lastMessageTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #createTime="{ row }">
        {{ row.createTime&&dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- 查看订单 -->
          <view-order :id="row.id" :operate-type="row.operateType" :is-basic-single="row.decorationType==='2'&&row.orderStage!=0"/>
          <t-link
            v-if="row.inGh === '0' && row.deleted === '0'"
            v-permission="['system:order:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <!-- 转派客服 -->
          <transfer-sale :ids="[row.id]" @request-success="handleDialogRequestSuccess" />
          <!-- 转派设计师 -->
          <transfer-designer
            :ids="[row.id]"
            :company-id="row.companyId"
            :phone="row.phone"
            :is-product-designer="row.decorationType==='2'"
            @request-success="handleDialogRequestSuccess"
          />
          <!-- 设置客户等级 -->
          <set-customer-level :id="row.id" @request-success="handleDialogRequestSuccess" />
          <!-- 设置客户标签 -->
          <set-customer-label :order-id="row.id" @request-success="handleDialogRequestSuccess" />
          <!-- <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:order:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm> -->
          <!-- 申请废单 -->
          <apply-order-delete v-if="row.saleId === userStore.userInfo.id" :order-id="row.id" approve-type="4" @request-success="handleDialogRequestSuccess" />
          <!-- 申请转设计延期 -->
          <apply-transfer-designer-extension  :order-id="row.id" approve-type="2" @request-success="handleDialogRequestSuccess" />
          <handle-set :id="row.id" @request-success="handleDialogRequestSuccess"/>
          <t-popconfirm content="确认要恢复该项吗？" @confirm="handleRestore({ id: row.id })" v-if="row.deleted==='1'">
            <t-link theme="primary"> 废单恢复 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="basicOrderCRUD"
      header="*订单"
      width="800px"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-row :gutter="[20, 20]" style="width: 100%">
        <t-col :span="6">
          <t-form-item label="订单类型" name="decorationType" :rules="[{ required: true, message: '请选择订单类型' }]">
            <t-select
              v-model:value="formData.decorationType"
              :options="dictionaryStore.get('decoration_order_type')"
              placeholder="请选择订单类型"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.decorationType = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户名称" name="name" :rules="[{ required: true, message: '请输入客户名称' }]">
            <t-input v-model:value="formData.name" placeholder="请输入客户名称" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户性别" name="sex" :rules="[{ required: true, message: '请选择客户性别' }]">
            <t-select
              v-model:value="formData.sex"
              :options="dictionaryStore.get('system_user_sex')"
              placeholder="请选择客户性别"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.sex = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户等级" name="customerLevel">
            <t-select
              v-model:value="formData.customerLevel"
              :options="dictionaryStore.get('decoration_order_customer_level')"
              placeholder="请选择客户等级"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.customerLevel = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="formData.customerLevel === '4'">
          <t-form-item
            v-if="formData.customerLevel === '4'"
            label="交房时间"
            name="handoverTime"
            :rules="[{ required: true, message: '请选择交房时间' }]"
          >
            <t-date-picker 
              allow-input
              v-model:value="formData.handoverTime"
              clearable
              default-time="23:59:59"
              enable-time-picker
              placeholder="请选择交房时间"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item
            label="手机号码"
            name="phone"
            :rules="[
              { required: !formData.wxCode, message: '请输入手机号码' },
              { telnumber: true, message: '请输入正确的手机号码' },
            ]"
          >
            <t-input
              v-model:value="formData.phone"
              placeholder="请输入手机号码"
              clearable
              :readonly="readonly"
              maxlength="11"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item
            label="微信号码"
            name="wxCode"
            :rules="[{ required: !formData.phone, message: '请输入微信号码' }]"
          >
            <t-input v-model:value="formData.wxCode" placeholder="请输入微信号码" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
            <t-cascader
              v-model:value="formData.adCode"
              :options="city.tree"
              :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
              placeholder="请选择归属城市"
              filterable
              clearable
              :readonly="readonly"
              value-type="full"
              @change="(value: any) => handleAdCodeChange(value, formData)"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="来源渠道" name="channelSource" :rules="[{ required: true, message: '请选择来源渠道' }]">
            <t-select
              v-model:value="formData.channelSource"
              :options="channelList"
              :keys="{ value: 'id', label: 'name' }"
              placeholder="请选择来源渠道"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.channelSource = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="楼盘名称" name="propertyName" :rules="[{ required: true, message: '请选择楼盘名称' }]">
            <t-select
              v-model:value="formData.propertyName"
              v-model:popup-visible="formData.popupVisible"
              placeholder="请选择楼盘名称"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.propertyName = null"
            >
              <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
                {{ _.name }}
                <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
              </t-option>
              <template #panelBottomContent>
                <!-- 快捷添加楼盘信息 -->
                <quick-add-property-info
                  @open="formData.popupVisible = false"
                  @close="getPropertyClose"
                />
              </template>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="详细地址" name="address">
            <t-input v-model:value="formData.address" placeholder="请输入详细地址" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="房屋户型" name="houseType" :rules="[{ required: true, message: '请选择房屋户型' }]">
            <t-select
              v-model:value="formData.houseType"
              :options="dictionaryStore.get('decoration_order_house_type')"
              placeholder="请选择房屋户型"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.houseType = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="房屋面积(㎡)" name="houseArea" :rules="[{ required: true, message: '请输入房屋面积' }]">
            <t-input-number
              v-model:value="formData.houseArea"
              placeholder="请输入房屋面积"
              :min="0"
              :allow-input-over-limit="false"
              clearable
              :readonly="readonly"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="归属公司" name="companyId" :rules="[{ required: true, message: '请选择归属公司' }]">
            <t-select
              v-model:value="formData.companyId"
              :options="companyList"
              :keys="{ value: 'id', label: 'name' }"
              placeholder="请选择归属公司"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.companyId = null"
            />
          </t-form-item>
        </t-col>
        <t-col v-if="mode === 'create'" :span="6">
          <t-form-item label="回访内容" name="lastMessage" :rules="[{ required: true, message: '请输入回访内容' }]">
            <t-textarea v-model:value="formData.lastMessage" placeholder="请输入回访内容" :readonly="readonly" />
          </t-form-item>
        </t-col>
      </t-row>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'BasicOrder',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { channelManageCRUD } from '@/api/config/common-config';
import { propertyManageCRUD } from '@/api/config/property';
import { basicOrderCRUD, restoreOrder } from '@/api/order/basic';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import QuickAddPropertyInfo from '@/pages/config/property/components/QuickAddPropertyInfo.vue';
import ViewOrder from '@/pages/order/details/components/ViewOrder.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import city from '@/utils/city';
import disposableParams from '@/utils/disposableParams';
import listToTree from '@/utils/listToTree';

import ApplyOrderDelete from '../single/components/ApplyOrderDelete.vue';
import ApplyTransferDesignerExtension from './components/ApplyTransferDesignerExtension.vue';
import SetCustomerLabel from './components/SetCustomerLabel.vue';
import SetCustomerLevel from './components/SetCustomerLevel.vue';
import TransferDesigner from './components/TransferDesigner.vue';
import HandleSet from './components/HandleSet.vue';
import TransferSale from './components/TransferSale.vue';
import { getAllSimpleUserlist, getSimpleUserListByDeptId, userCRUD } from '@/api/system/user';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 渠道列表
const channelList = ref([]);
// 处理获取渠道列表
const handleGetChannelList = () => {
  const params = {
    pageSize: -1,
  };
  channelManageCRUD
    .page(params)
    .then((data) => {
      channelList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetChannelList();
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门树
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList()
    .then((data) => {
      simpleDeptTree.value = listToTree(data);
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetSimpleDeptTree();
// 公司列表
const companyList = ref([]);
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();
// 客服列表
const saleList = ref([]);
// 处理获取客服列表
const handleGetSaleList = (deptId: any) => {
  if(!deptId) return
  getSimpleUserListByDeptId({deptId:deptId,pageSize:-1})
    .then((data) => {
      saleList.value = data;
      customSearchRef.value.params.saleId=null
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 上报人列表
const reporteList = ref([]);
// 处理获取上报人列表
const handleGetreporteList = () => {
  getAllSimpleUserlist()
    .then((data) => {
      reporteList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetreporteList()
const getPropertyClose = () => {
  customDialogRef.value.formData.popupVisible = true
  
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
      customDialogRef.value.formData.propertyName=propertyInfoList.value[0].id
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });

}
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'name', title: '客户名称 ', width: 80 },
  { colKey: 'phone', title: '手机号码', width: 110 },
  { colKey: 'propertyName', title: '楼盘名称', width: 200,},
  { colKey: 'houseType', title: '房屋户型', width: 80 },
  { colKey: 'lastMessage', title: '最后记录内容', width: 200, ellipsis: true },
  { colKey: 'reporterName', title: '上报人', width: 100 },
  { colKey: 'saleName', title: '客服', width: 80 },

  { colKey: 'designerName', title: '设计师', width: 100 },
  { colKey: 'decorationType', title: '订单类型', width: 80 },
  { colKey: 'orderStage', title: '订单阶段', width: 80 },

  { colKey: 'customerLevel', title: '客户等级', width: 80 },

  { colKey: 'wxCode', title: '微信号码', width: 110 },
  { colKey: 'adCode', title: '归属城市', width: 190 },
  { colKey: 'channelSource', title: '来源渠道', width: 130 },

  // { colKey: 'address', title: '详细地址', width: 100 },

  { colKey: 'houseArea', title: '房屋面积(㎡)', width: 100 },


  { colKey: 'lastMessageTime', title: '最后记录时间', width: 170 },
  { colKey: 'createTime', title: '创建时间', width: 170 },
  { colKey: 'operation', title: '操作', width: 220, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
    operateType: '',
  });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  if(customSearchRef.value.params.orderIds||toDoTreeJumpParams.orderIds) {
    customSearchRef.value.params.orderStage = ''
    customSearchRef.value.params.deleted = ''
    customSearchRef.value.params.inGh = ''
  }
  const params: Record<string, any> = {
    orderIds: toDoTreeJumpParams.orderIds,
    operateType: toDoTreeJumpParams.operateType,
    ...customSearchRef.value.params,
  };
  if (!params.adCode.length) {
    delete params.province;
    delete params.city;
    delete params.area;
  }
  if (!params.cjsj.length) {
    delete params.beginTime;
    delete params.endTime;
  }
  customTableRef.value.initTable(params);
  customSearchRef.value.params.orderIds =''
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 处理表格请求成功
const handleTableRequestSuccess = ({ params, data }: Record<string, any>) => {
  data.forEach((item: Record<string, any>) => {
    item.operateType = params.operateType;
  });
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable();
})
// 选中行的keys
const selectedRowKeys = ref([]);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetPropertyInfoList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
  selectedRowKeys.value = []
};
// // 处理删除
// const handleDelete = (params: Record<string, any>) => {
//   basicOrderCRUD
//     .delete(params)
//     .then(() => {
//       MessagePlugin.success('删除成功');
//       handleRefreshTable();
//     })
//     .catch(({ message }) => {
//       MessagePlugin.error(message);
//     });
// };
// // 处理废单恢复
const handleRestore = (params: Record<string, any>) => {
  restoreOrder(params)
    .then(() => {
      MessagePlugin.success('恢复成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.province = value[0] || '';
  params.city = value[1] || '';
  params.area = value[2] || '';
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.adCode = [];
  if (params.province) params.adCode.push(params.province);
  if (params.city) params.adCode.push(params.city);
  if (params.area) params.adCode.push(params.area);
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
const tableTotal = ref<Record<string,any>>({})
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  tableTotal.value = data.data
  return data
};
const hasData = computed(() => {
  return Object.keys(tableTotal.value).length > 0;
});
const processedStages = computed(() => {
  if(!hasData.value) return []
  return [
    {label:'上报',value:'shangbao'},
    {label:'转设计',value:'designer'},
  ].map(stage => {
        const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];

        return {
          ...stage,
          ids,
          count: ids.length,
          
        };
      }).filter(stage => stage.count > 0);
});
const designStages = computed(() => {
  if(!hasData.value) return []
  return dictionaryStore.get('order_designer_stage').map(stage => {
        const ids = tableTotal.value.desStageMap[stage.value] ? tableTotal.value.desStageMap[stage.value].split(',') : [];

        return {
          ...stage,
          ids,
          count: ids.length,
          
        };
      }).filter(stage => stage.count > 0);
});
// 所有延期数据
const overdueStages = computed(() => {
  if(!hasData.value) return []
 return [
    {label:'1次进入公海',value:'1GongHai'},
    {label:'2次及以上进入公海',value:'2GongHai'},
  ].map(stage => {
  const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];
    return {

      ...stage,
          ids,
          count: ids.length,
    };
  }).filter(stage => stage.count > 0);

});
// 点击条数
const handleClick= (stageValue:any,ids:any)=> {
  customSearchRef.value.params.orderIds = ids.toString()
  handleInitTable()
}
</script>

<style lang="less" scoped>
.stage-item {
  margin-right: 6px;
}
</style>
